package cn.cycleif.advice;

import cn.cycleif.constants.MsgConstant;
import cn.cycleif.exception.BaseException;
import cn.cycleif.util.R;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

import static cn.cycleif.enums.ResultCodeEnum.*;

/**
 * &#064;Date: 24/04/22-18:14
 * &#064;Description:
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

  @ExceptionHandler
  public R<String> exceptionHandler(BaseException ex) {
    log.error("业务异常：{}", ex.getMessage());
    ex.printStackTrace();
    return R.error(ex.getMessage());
  }

  @ExceptionHandler
  public R<String> exceptionHandler(NotLoginException ex) {
    log.error("未登录异常：{}", ex.getMessage());
    return R.error(ERROR_NOT_LOGIN);
  }

  @ExceptionHandler
  public R<String> exceptionHandler(NotRoleException ex) {
    log.error("无角色异常：{}", ex.getMessage());
    return R.error(ERROR_NO_PERMISSION);
  }

  @ExceptionHandler
  public R<String> exceptionHandler(Exception ex) {
    log.error("未知异常：{}", ex.getMessage());
    ex.printStackTrace();
    // return R.error(ERROR_UNKNOWN);
    return R.error(ex.getMessage());
  }

  @ExceptionHandler
  public R<String> exceptionHandler(MethodArgumentNotValidException ex) {
    log.error("参数校验异常：{}", ex.getMessage());
    ex.printStackTrace();
    return R.error(ERROR_REQUEST_FORMAT);
  }
  @ExceptionHandler
  public R<String> exceptionHandler(NotPermissionException ex) {
    log.error("无权限异常：{}", ex.getMessage());
    ex.printStackTrace();
    return R.error(ERROR_NO_PERMISSION);
  }

  /**
   * 处理SQL完整性异常
   */
  @ExceptionHandler
  public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
    // Duplicate entry 'xx' for key 'xx'
    String message = ex.getMessage();
    if (message.contains("Duplicate entry")) {
      String[] split = message.split(" ");
      String   entry = split[2];
      String   msg   = entry + MsgConstant.ALREADY_EXISTS;
      return R.error(msg);
    } else {
      return R.error(ERROR_DATABASE);
    }
  }

}
